package com.koo.modules.cx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.koo.common.utils.MyStrUtil;
import com.koo.common.utils.PageUtils;
import com.koo.common.utils.Query;
import com.koo.framework.query.MyBatisPlusUtil;
import com.koo.modules.cx.dao.CxInspectionOrderDao;
import com.koo.modules.cx.entity.CxInspectionOrderDetailEntity;
import com.koo.modules.cx.entity.CxInspectionOrderEntity;
import com.koo.modules.cx.service.CxInspectionOrderDetailService;
import com.koo.modules.cx.service.CxInspectionOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class CxInspectionOrderServiceImpl extends ServiceImpl<CxInspectionOrderDao, CxInspectionOrderEntity> implements CxInspectionOrderService {

    @Autowired
    private CxInspectionOrderDetailService inspectionOrderDetailService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        Object key = params.get("key");
        LambdaQueryWrapper<CxInspectionOrderEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(MyStrUtil.isNotEmpty(key), CxInspectionOrderEntity::getInspectionOrderDate, key)
                .or().eq(MyStrUtil.isNotEmpty(key), CxInspectionOrderEntity::getInspectionOrderNo, key);

        IPage<CxInspectionOrderEntity> page = this.page(
                new Query<CxInspectionOrderEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<CxInspectionOrderEntity> listOutOrders(Integer limit) {
        return baseMapper.listOutOrders(limit);
    }

    @Override
    public boolean findHasOrderByHeadNo(String headQuarterAllotNo) {
        Integer count = baseMapper.selectCount(MyBatisPlusUtil.createEQWrapper(new Object[]{headQuarterAllotNo}, "headQuarterAllotNo"));
        return MyStrUtil.isNotEmpty(count) && count != 0;
    }

    @Override
    public void insertByListAndUpdateState(List<CxInspectionOrderEntity> outOrders, List<CxInspectionOrderDetailEntity> orderDetails) {
        outOrders.forEach(item -> {
            item.setStatus(1);
        });
        this.saveBatch(outOrders);
        //添加明细
        inspectionOrderDetailService.saveBatch(orderDetails);

    }

}